import React, { Component } from 'react'

import { SearchBar } from 'antd-mobile'

import request from '../../../utils/api.js'
import getCurrentCity from '../../../utils/localtion.js'

import styles from './index.module.css'

export default class Search extends Component {
    // 当前城市id
    cityId = ''

    state = {
        // 搜索框的值
        searchTxt: '',
        tipsList: []
    }

    onChange= (value) => {
        this.setState({
            searchTxt: value
        })
    }

    queryData = async () => {
        // 根据关键字查询小区名称列表
        const { searchTxt } = this.state
        // 获取当前城市
        const city = await getCurrentCity()
        const res = await request({
            method: 'get',
            url: '/area/community',
            params: {
                // 搜索关键字
                name: searchTxt,
                // 表示当前城市的唯一编号
                id: city.value
            }
        })
        console.log(res)
        this.setState({
            tipsList: res.body
        })
    }

    // 渲染搜索结果列表
    renderTips = () => {
        const { tipsList } = this.state
        return tipsList.map(item => (
            <li
                onClick={() => {
                    // 跳转到添加页面
                    this.props.history.replace('/rent/add', {
                        cid: item.community,
                        cname: item.communityName
                    })
                }}
                key={item.community}
                className={styles.tip}>
                {item.communityName}
            </li>
        ))
    }

    render() {
        const { history } = this.props
        const { searchTxt } = this.state

        return (
            <div className={styles.root}>
                {/* 搜索框 */}
                <SearchBar
                    placeholder="请输入小区或地址"
                    value={searchTxt}
                    onSubmit={this.queryData}
                    onChange={this.onChange}
                    onCancel={() => history.replace('/rent/add')}
                    showCancelButton={true}
                />

                {/* 搜索提示列表 */}
                <ul className={styles.tips}>{this.renderTips()}</ul>
            </div>
        )
    }
}